package com.axend.aerosense.dev.viewmodel;

import android.app.Activity;
import android.text.TextUtils;

import androidx.lifecycle.MutableLiveData;

import com.alibaba.android.arouter.launcher.ARouter;
import com.axend.aerosense.base.bean.BaseStringBean;
import com.axend.aerosense.base.impl.IBaseView;
import com.axend.aerosense.base.impl.ILoadDataResult;
import com.axend.aerosense.base.storage.MmkvHelper;
import com.axend.aerosense.base.viewmodel.CustomBaseViewModel;
import com.axend.aerosense.common.UrlApi;
import com.axend.aerosense.common.bean.RadarBean;
import com.axend.aerosense.common.config.Gobal;
import com.axend.aerosense.common.router.RouterActivityPath;
import com.axend.aerosense.common.ui.LoadingDialog;
import com.axend.aerosense.common.util.JsonUtil;
import com.axend.aerosense.dev.R;
import com.axend.aerosense.dev.entity.DevRadarSettingBean;
import com.axend.aerosense.dev.entity.DevRadarSettingResBean;
import com.axend.aerosense.dev.entity.RadarNetworkBean;
import com.axend.aerosense.network.EasyHttp;
import com.axend.aerosense.network.cache.model.CacheMode;
import com.axend.aerosense.network.callback.ProgressDialogCallBack;
import com.axend.aerosense.network.callback.SimpleCallBack;
import com.axend.aerosense.network.exception.ApiException;
import com.blankj.utilcode.util.ToastUtils;

import java.math.BigDecimal;

import io.reactivex.disposables.Disposable;

public class DevWavveSettingViewModel extends CustomBaseViewModel<DevRadarSettingResBean> {

    private static final double MIN_HEIGHT_METRE = 0.18f;  //米转英尺
    private static final double MAX_HEIGHT_METRE = 2.5f;  //英尺转米

    private Disposable disposable;
    private RadarBean radarBean;
    private String token;

    /**
     * 1：床头
     * 2：天花板
     */
    public MutableLiveData<Integer> checkedType = new MutableLiveData<>(2);
    //输入的数据
    public MutableLiveData<String> inputFoot = new MutableLiveData<>();

    public DevWavveSettingViewModel(IBaseView baseViewImpl, ILoadDataResult<DevRadarSettingResBean> loadDataResultImpl) {
        super(baseViewImpl, loadDataResultImpl);
        token = MmkvHelper.getInstance().getMmkv().decodeString(Gobal.SAVE_KEY.TOKEN);
    }

    public void setRadarBean(RadarBean radarBean) {
        this.radarBean = radarBean;
    }

    @Override
    public void onLoad() {
        disposable = EasyHttp.post(UrlApi.URL.GetRadarSettings.getUrl())
                .cacheMode(CacheMode.NO_CACHE)
                .headers("token", token)
                .upJson(JsonUtil.toJson(new RadarNetworkBean(radarBean.getRadarUuid())))
                .execute(new SimpleCallBack<DevRadarSettingResBean>() {
                    @Override
                    public void onTokenExpire() {
                        ToastUtils.showShort(R.string.common_login_first);
                        ARouter.getInstance().build(RouterActivityPath.Login.PAGE_LOGIN_HOME).withBoolean("jumpMainPage", true).greenChannel().navigation();
                    }

                    @Override
                    public void onError(ApiException e) {
                        e.printStackTrace();
                        ToastUtils.showLong(e.getMessage());
                        loadDataFail(e.getMessage());
                    }

                    @Override
                    public void onSuccess(DevRadarSettingResBean bean) {
                        loadDataSuccess(bean);
                        if (null == bean && null == bean.getRadarInfo()) return;

                        setInstallHeightByFoot(bean.getRadarInfo().getInstallHeight());
                        checkedType.setValue(bean.getRadarInfo().getInstallMode());
                    }
                });
    }


    /**
     * 保存雷达参数
     */
    public void setSettings(Activity activity){
        float height = getInstallHeightByMetre();
        if(height < MIN_HEIGHT_METRE || height > MAX_HEIGHT_METRE){
            return;
        }
        DevRadarSettingBean devRadarSettingBean = new DevRadarSettingBean(
                activity.getString(radarBean.getType().getName()),
                radarBean.getRadarUuid(),
                checkedType.getValue(),
                height,
                radarBean.getType().get());

        disposable = EasyHttp.post(UrlApi.URL.SetRadarSettings.getUrl())
                .cacheMode(CacheMode.NO_CACHE)
                .headers("token", token)
                .upJson(JsonUtil.toJson(devRadarSettingBean))
                .execute(new ProgressDialogCallBack<BaseStringBean>(LoadingDialog.getProgressDialog(activity)) {
                    @Override
                    public void onTokenExpire() {
                        ToastUtils.showShort(R.string.common_login_first);
                        ARouter.getInstance().build(RouterActivityPath.Login.PAGE_LOGIN_HOME).withBoolean("jumpMainPage", true).greenChannel().navigation();
                    }

                    @Override
                    public void onError(ApiException e) {
                        dismissProgress();
                        e.printStackTrace();
                        ToastUtils.showLong(e.getMessage());
                    }

                    @Override
                    public void onSuccess(BaseStringBean bean) {
                        dismissProgress();
                        ToastUtils.showLong(R.string.common_success);
                        activity.onBackPressed();
                    }
                });
    }


    public boolean checkInput(MutableLiveData<String> foot){
        if (TextUtils.isEmpty(foot.getValue())) return true;

        float num = 0;
        try {
            num = Float.parseFloat(foot.getValue());
            return num >= MIN_HEIGHT_METRE && num <= MAX_HEIGHT_METRE;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    public String format(MutableLiveData<String> foot){
        if (TextUtils.isEmpty(foot.getValue())) return foot.getValue();

        return String.format("%.1f", Float.parseFloat(foot.getValue()));
    }

    public void setChecked(Integer integer){
        checkedType.setValue(integer);
    }

    // 获取安装高度（m）
    public float getInstallHeightByMetre(){
        float value = 0;
        try{
            value = Float.parseFloat(inputFoot.getValue());
        }catch (Exception e){

        }
        return value;
    }

    //设置安装高度（m）
    public void setInstallHeightByFoot(float metre){
        inputFoot.setValue(String.valueOf(metre));
    }

    @Override
    protected void onCleared() {
        super.onCleared();
        if (null == disposable) return;

        disposable.dispose();
    }
}
